<template>
    <div class="container">
        <!--引入粒子特效-->
        <div class="bkpro-login-canvas" style="position:relative;z-index: -999;">
            <Particles id="tsparticles" :options="options" />
        </div>
        <div class="loginForm-container">
            <h1 style="text-align:center">博客管理系统</h1>
            <el-tabs v-model="activeName">
                <el-tab-pane label="登录" name="login">
                    <el-form ref="loginFormRef" :model="loginForm" label-width="80px" :rules="rules" class="loginForm">
                        <el-form-item prop="account" label="账号">
                            <el-input v-model.trim="loginForm.account" clearable autofocus ref="accountRef"
                                @keyup.enter.native="login(loginFormRef)" />
                        </el-form-item>
                        <el-form-item prop="password" label="密码">
                            <el-input v-model.trim="loginForm.password" type="password" show-password clearable
                                @keyup.enter.native="login(loginFormRef)" />
                        </el-form-item>
                        <el-form-item prop="code" label="验证码">
                            <div style="display: flex;">
                                <el-input type="text" ref="iptRef" v-model="loginForm.code"
                                    @keyup.enter.native="login(loginFormRef)" />
                                <img :src="codeUrl" alt="验证码" class="code-img" @click="resetCode">
                            </div>
                        </el-form-item>
                        <el-form-item>
                            <div class="btn-container">
                                <el-button type="primary" @click="login(loginFormRef)">登录</el-button>
                                <el-button @click="resetForm(loginFormRef)">重置</el-button>
                                <el-button link type="danger" @click="activeName = 'register'">无账号?去注册</el-button>
                            </div>
                        </el-form-item>

                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="注册" name="register">
                    <el-form ref="registerFormRef" :model="registerForm" label-width="80px" :rules="rules"
                        class="loginForm">
                        <el-form-item prop="account" label="账号">
                            <el-input v-model.trim="registerForm.account" clearable />
                        </el-form-item>
                        <el-form-item prop="password" label="密码">
                            <el-input v-model.trim="registerForm.password" type="password" show-password clearable />
                        </el-form-item>
                        <el-form-item prop="spassword" label="确定密码">
                            <el-input v-model.trim="registerForm.spassword" type="password" show-password clearable />
                        </el-form-item>
                        <el-form-item>
                            <div class="btn-container">
                                <el-button type="primary" @click="register(registerFormRef)">注册</el-button>
                                <el-button @click="resetForm(registerFormRef)">重置</el-button>
                                <el-button link type="danger" @click="activeName = 'login'">有账号?去登陆</el-button>
                            </div>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template> 
<script setup lang='ts'>
import { ref, reactive, onMounted, nextTick, inject } from 'vue'
import { useRouter } from 'vue-router';
import { ElMessage, type FormInstance, type FormRules, type InputInstance, type TabsPaneContext } from 'element-plus'
import { loginAccount, registerAccount } from '../api'
import { useUserInfoStore } from '../stores';
import { options } from '@/utils'

const socket: any = inject('socket')

const userInfoStore = useUserInfoStore()
interface loginForm {
    account: string,
    password: string,
    code: string
}
const activeName = ref('login')
const router = useRouter()
const codeUrl = ref<string>('http://localhost:3000/user-account/code')
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()
const iptRef = ref()
const accountRef = ref()
const loginForm = reactive<loginForm>({
    account: '',
    password: '',
    code: '',
})
const registerForm = reactive({
    account: '',
    password: '',
    spassword: ''
})

const rules = reactive<FormRules>({
    account: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 6, max: 12, message: '长度为6-12个字符', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9]+$/, message: '只能输入数字和字母', trigger: 'blur' }

    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 12, message: '长度为6-12个字符', trigger: 'blur' },
        { pattern: /^(?![\d]+$)(?![a-z]+$)(?![A-Z]+$)(?![!<>#$?@%^&*,]+$)[\da-zA-Z!<>#$?@%^&*,]{6,12}$/, message: '至少包含大小写字母、数字和特殊字符其中两种', trigger: 'blur' }
    ],
    spassword: [
        { required: true, message: '请输入确定密码', trigger: 'blur' },
        { min: 6, max: 15, message: '密码长度在 6 到 12 个字符', trigger: 'blur' },
        {
            validator(rule, value, callback) {
                if (value !== registerForm.password) {
                    callback(new Error('两次输入密码不一致!'))
                    return;
                }
                callback();
            },
            trigger: 'blur'
        },
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
    ]
})


//登录
const login = (formEl: FormInstance | undefined) => {
    if (!formEl) return    //校验
    formEl.validate(async (valid, error) => {
        if (valid) {
            const res = await loginAccount(loginForm)
            const { data, data: { code }, data: { msg } } = res
            if (code === 200) {
                const { data: { data } } = res
                await userInfoStore.saveUserInfo(data.uuid)
                ElMessage({
                    message: msg,
                    type: 'success',
                })
                //登录成功
                setTimeout(() => {
                    router.push({ name: 'layout' })
                    socket.emit('login', userInfoStore.userInfo.id)
                }, 1000)
            } else {
                ElMessage({
                    message: msg,
                    type: 'error'
                })
                resetCode()
                if (data.code == 400) {
                    //验证码错误
                    iptRef.value.clear()
                    iptRef.value.focus()
                } else {
                    resetForm(formEl)
                    accountRef.value.focus()
                }
            }
        } else {
            return false
        }
    })
}


//注册
const register = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid, error) => {
        if (valid) {
            const { account, password } = registerForm
            const registerDto = { account, password }
            const res = await registerAccount(registerDto)
            const { data } = res
            if (data.code === 200) {
                //注册成功
                ElMessage({
                    message: data.msg,
                    type: 'success',
                })
            } else {
                //注册成功
                ElMessage({
                    message: data.msg,
                    type: 'error',
                })
                resetForm(formEl)
            }
        } else {
            console.log('error submit!', error)
            return false
        }
    })
}

//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}


//重置验证码
const resetCode = () => {
    codeUrl.value = codeUrl.value + '?' + new Date().getTime();
}



</script>
<style scoped lang="scss">
.code-img {
    width: 120px; 
    height: 30px;
    cursor: pointer;
    margin-left: 10px;
}

.container {
    position: relative;
    height: 100vh;
    background-image: url('@/assets/images/bg.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    z-index: 0;

    .loginForm-container {
        position: absolute;
        min-width: 400px;
        width: 400px;
        height: 200px;
        background-color: rgba(255, 255, 255, 0.8);
        padding: 20px 30px 80px;
        border-radius: 10px;
        left: 50%;
        top: 40%;
        transform: translateX(-50%) translateY(-50%);
    }

    .btn-container {
        width: 100%;
        display: flex;
        justify-content: space-between;
    }

}
</style>